////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// The MIT License (MIT)                                                      //
//                                                                            //
// Copyright (c) 2013 Charles Teague                                          //
//                                                                            //
// Permission is hereby granted, free of charge, to any person obtaining a    //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation  //
// the rights to use, copy, modify, merge, publish, distribute, sublicense,   //
// and/or sell copies of the Software, and to permit persons to whom the      //
// Software is furnished to do so, subject to the following conditions:       //
//                                                                            //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software.                        //
//                                                                            //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING    //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER        //
// DEALINGS IN THE SOFTWARE.                                                  //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


using RPSDAL;
using RPSDAL.EntityClasses;
using RPSDAL.DaoClasses;
using RPSDAL.FactoryClasses;
using RPSDAL.HelperClasses;
using RPSDAL.CollectionClasses;

using SD.LLBLGen.Pro.ORMSupportClasses;

public partial class AssignCalls : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        if (Parameters.LoggedUser != -1) 
        {
            UserEntity eUser = new UserEntity(Parameters.LoggedUser);
            RoleEntity eRole = new RoleEntity(eUser.RoleId);

            if (!eRole.HasAssignCall) 
            {
                Parameters.LoggedUser = -1;
                Response.Redirect("Default.aspx");
                return;
            }
        }        
    }

    private void LoadCalls()
    {
        DataTable dtFields = new DataTable();
        ResultsetFields fields = new ResultsetFields(9);

        fields.DefineField(ContactFieldIndex.Phone, 0, "Phone");
        fields.DefineField(ContactFieldIndex.MobilePhone, 1, "MobilePhone");
        fields.DefineField(ContactFieldIndex.Name, 2, "Name");
        fields.DefineField(BusinessRuleFieldIndex.From, 3, "From");
        fields.DefineField(BusinessRuleFieldIndex.To, 4, "DaysTo");
        fields.DefineField(UserFieldIndex.ConnectName, 5, "UserName");
        fields.DefineField(BusinessRuleFieldIndex.CallReason, 6, "CallReason");
        fields.DefineField(CallFieldIndex.CallId, 7, "CallId");
        fields.DefineField(ContactFieldIndex.ContactVisitDate, 8, "ContactVisitDate");

        fields[3].ExpressionToApply = new Expression(ContactFields.ContactVisitDate, ExOp.Add, BusinessRuleFields.From);
        fields[4].ExpressionToApply = new Expression(ContactFields.ContactVisitDate, ExOp.Add, BusinessRuleFields.To);

        RelationCollection relations = new RelationCollection();
        relations.Add(CallEntity.Relations.UserEntityUsingUserId, JoinHint.Left);
        relations.Add(CallEntity.Relations.BusinessRuleEntityUsingBusinessRuleId);
        relations.Add(CallEntity.Relations.ContactEntityUsingContactId);

        IPredicateExpression filter = new PredicateExpression();
        filter.Add(CallFields.Done == false);

        /*fields[0].ExpressionToApply = new Expression(
            new Expression(EntityFieldFactory.Create(ContactFieldIndex.Phone), ExOp.Add,"\t/\t"),
            ExOp.Add,
            EntityFieldFactory.Create(ContactFieldIndex.MobilePhone));
          */

        TypedListDAO dao = new TypedListDAO();
        SortExpression sortExp = new SortExpression(new SortClause(fields["Name"], SortOperator.Ascending));
        dao.GetMultiAsDataTable(fields, dtFields, 0, sortExp, filter, relations, false, null, null, 0, 0);


        grdCalls.DataSource = dtFields;
        grdCalls.DataBind();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            btnCheckAll.Attributes.Add("OnClick", "this.value=CheckAll('aspnetForm');return false;");
            Session["CHECKED_ITEMS"] = null;

            grdCalls.PageSize = Parameters.PageSize;
            LoadCalls();      

            if (!String.IsNullOrEmpty(Request.QueryString["id"]))
            {
                UserEntity eUser = new UserEntity(Convert.ToInt32(Global.DecryptString(Request.QueryString["id"].ToString())));
                

                lblUser.Text = eUser.ConnectName;
                lblMaxNumberCalls.Text = eUser.MaxCallPerWeek.ToString();

            }

        }
    }

    #region user interface

    protected void AssignSelectedCalls(object sender, EventArgs e)
    {
        ArrayList callIdList = (ArrayList)Session["CHECKED_ITEMS"];
        if (callIdList != null)
        {
            for (int i = 0; i < callIdList.Count; i++)
            {
                CallEntity eCall = new CallEntity(Convert.ToInt32(callIdList[i]));
                eCall.UserId = Convert.ToInt32(Global.DecryptString(Request.QueryString["id"].ToString()));
                eCall.Save();
            }
        }


        bool assignedCall = false;
        for (int i = 0; i < grdCalls.Rows.Count; i++) 
        {
            if (((CheckBox)grdCalls.Rows[i].Cells[7].FindControl("ckAssignCall")).Checked) 
            {
                assignedCall = true;
                CallEntity eCall = new CallEntity((int)(grdCalls.DataKeys[i].Value));
                eCall.UserId = Convert.ToInt32(Global.DecryptString(Request.QueryString["id"].ToString()));
                eCall.Save();
            }
        }

        if (assignedCall)
        {
            LoadCalls();
            lblAssignedMessage.Visible = true;
        }
        //Response.Redirect("UserCallsList.aspx");
    }

    #endregion user interface




    protected void btnClose_Click(object sender, EventArgs e)
    {
        Response.Redirect("UserCallsList.aspx");
    }

    
    protected void grdCalls_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        RememberOldValues();
        grdCalls.PageIndex = e.NewPageIndex;
        LoadCalls();      
        RePopulateValues();
    }


    private void RememberOldValues()
    {
        ArrayList callIdList = new ArrayList();
        int index = -1;
        foreach (GridViewRow row in grdCalls.Rows)
        {
            index = (int)(grdCalls.DataKeys[row.RowIndex].Value);
            bool result = ((CheckBox)row.FindControl("ckAssignCall")).Checked;

            // Check in the Session
            if (Session["CHECKED_ITEMS"] != null)
                callIdList = (ArrayList)Session["CHECKED_ITEMS"];
            if (result)
            {
                if (!callIdList.Contains(index))
                    callIdList.Add(index);
            }
            else
                callIdList.Remove(index);
        }
        if (callIdList != null && callIdList.Count > 0)
            Session["CHECKED_ITEMS"] = callIdList;
    }

    private void RePopulateValues()
    {
        ArrayList callIdList = (ArrayList)Session["CHECKED_ITEMS"];
        if (callIdList != null && callIdList.Count > 0)
        {
            foreach (GridViewRow row in grdCalls.Rows)
            {
                int index = (int)(grdCalls.DataKeys[row.RowIndex].Value);
                if (callIdList.Contains(index))
                {
                    CheckBox myCheckBox = (CheckBox)row.FindControl("ckAssignCall");
                    myCheckBox.Checked = true;
                }
            }
        }
    }    

}
